/**
 * created by zt on 2018/04/20
 */
import React from "react";
import { Card, Spin, Table, Button, Popconfirm, Popover, Icon } from "antd";
// service 服务
import ConfigurationCenterService from "containers/setting/configuration-center/configuration-center.service";
// 数据查询条件
import "styles/setting/configuration-center/configuration-detail.scss";

import { connect } from "react-redux";
import SlideFrame from "components/slide-frame";
import EditRule from "containers/setting/configuration-center/configuration-detail/edit-rule";
import ConfigurationCenterModel from "containers/setting/configuration-center/configuration-center.model";
import { messages, deepCopy } from "share/common";
import menuRoute from "routes/menuRoute";
import ResizeTable from "components/resize-table";

class ConfigurationDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true, // 加载状态
      data: [], // 数据
      query: {}, // 查询条件
      columns: [], // 表头
      tableData: [], // 表单内容
      showRuleDetail: false, // 显示规则详情
      title: "", // 编辑框标题
      currentRule: "", // 当前的规则
      rule: {}, // 规则格式
      configurationDetail: menuRoute.getRouteItem("configuration-center"), //配置中心route
    };
  }

  componentWillMount() {
    this.initConfigurationQuery();
  }

  componentDidMount() {
    this.getData();
  }

  // 初始化 配置项查询值
  initConfigurationQuery = () => {
    this.setState({
      query: {
        page: 0,
        size: 1000,
        itemIds: [this.props.params.id],
        tenantId: this.props.tenantInfo.id, // 租户id
        getDetail: "Y", // 获取配置项详情
      },
    });
  };

  /**
   * @description 获取后台数据
   *
   * */
  getData = () => {
    const { query } = this.state;
    this.setState({
      loading: true,
    });
    ConfigurationCenterService.getConfigurationList(query).then((res) => {
      const data = res.data.rows[0];
      const { columns, rule } = this.configFactorsHandle({
        configFactors: data.configFactors,
        configItem: data.configItem,
      });
      const tableData = this.tableDataHandle({
        configRules: data.configRules,
        configFactors: data.configFactors,
        configItem: data.configItem,
      });
      this.setState({
        data,
        columns,
        tableData,
        rule,
        loading: false,
        showRuleDetail: false,
      });
    });
  };

  /**
   * @description configFactors数据处理
   * @param configFactors ConfigFactors
   * @param configItem ConfigItem
   *
   * */
  configFactorsHandle = ({ configFactors, configItem }) => {
    const columns = []; // 表头
    let rule = {}; // 默认规则格式
    const level = {
      // 优先级
      title: messages("setting.key270" /*优先级*/),
      key: "priority",
      dataIndex: "priority",
      width: 100,
    };
    // 默认规则格式
    rule = deepCopy(ConfigurationCenterModel.configurationRule);
    rule.configRule.configItemId = this.props.params.id;

    columns.push(level);

    configFactors.map((item) => {
      // 如果当前值为隐藏的话 表格不显示
      if (item.hide !== "Y") {
        const tableHeadItem = {
          title: item.factorName,
          key: item.factorCode,
          dataIndex: item.factorCode,
        };
        columns.push(tableHeadItem);
      }
      const ruleItem = {
        factorCode: item.factorCode,
        factorValue: null,
        factorValueDesc: null,
      };
      rule.configRuleFactors.push(ruleItem);
    });
    // 校验结果
    const validateRules = {
      /* title: messages('configuration.detail.validateResult'),*/
      title: messages("setting.key271" /*校验结果*/),
      key: "validateResult",
      dataIndex: "validateResult",
      width: "20%",
      render: (value) => <Popover content={value}>{value}</Popover>,
    };

    columns.push(validateRules);
    const ruleItem = {
      factorCode: configItem.itemCode,
      factorValue: null,
      factorValueDesc: null,
    };
    rule.configRuleFactors.push(ruleItem);
    // 获取
    const actions = this.getTableActions();
    columns.push(actions);
    return { columns, rule };
  };

  /**
   * @description 获取表格操作列数据
   *
   * */
  getTableActions = () => {
    const title = messages("setting.key272" /*确认删除吗？*/);
    const ok = messages("common.ok"); // 确认删除提示文案
    const cancel = messages("common.cancel"); // 取消删除提示文案
    const deleteBtn = messages("common.delete"); // 删除按钮文案

    return {
      title: messages("setting.key273" /*操作*/),
      key: "action",
      width: 100,
      render: (rule) => (
        <Popconfirm
          title={title}
          placement="topRight"
          okText={ok}
          cancelText={cancel}
          onConfirm={() => this.handleDeleteRule(rule)}
        >
          <a
            href="javascript:void(0);"
            onClick={(e) => {
              e.preventDefault();
              e.stopPropagation();
            }}
          >
            {deleteBtn}
          </a>
        </Popconfirm>
      ),
    };
  };

  /**
   * @description 表格显示数据处理
   * @param configRules ConfigRule[]
   * @param configFactors ConfigFactor[]
   *
   * */
  tableDataHandle = ({ configRules, configFactors, configItem }) => {
    const tableData = []; // 表格数据
    // 如果规则有数据 则处理规则数据
    if (Array.isArray(configRules) && configRules.length > 0) {
      configRules.map((configRule) => {
        const tableItem = {
          id: configRule.configRule.id,
          priority: configRule.configRule.priority,
        };
        configFactors.map((item) => {
          tableItem[item.factorCode] =
            (configRule.configRuleFactorMap[item.factorCode] &&
              configRule.configRuleFactorMap[item.factorCode]
                .factorValueDesc) ||
            "-";
        });
        // 校验结果
        if (configItem.resultType === "DATALIST") {
          const arrays = JSON.parse(
            JSON.parse(JSON.stringify(configRule.configRule.valueName))
          );
          configRule.configRule.valueName = (
            <div>
              {arrays.map((item) => {
                return (
                  <div>
                    {item.fieldLabel}：{item.valueDesc || "-"}
                  </div>
                );
              })}
            </div>
          );
        }
        tableItem.validateResult = configRule.configRule.valueName;
        tableData.push(tableItem);
      });
    }
    return tableData;
  };

  /**
   *@description 添加规则
   * */
  handleAdd = () => {
    const { rule, tableData } = this.state;
    const maxLevel =
      tableData.length > 0
        ? Math.max.apply(
            null,
            tableData.map((item) => item.priority)
          )
        : 0;
    rule.configRule.priority = maxLevel + 1;

    this.setState({
      currentRule: rule,
      title: messages("common.add"),
      showRuleDetail: true,
    });
  };

  /**
   *@description 删除规则
   *@param rule tableItem
   * */
  handleDeleteRule = (rule) => {
    ConfigurationCenterService.deleteRule(rule.id).then(() => {
      this.getData();
    });
  };

  /**
   * @description 从数据中获取当前规则数据
   * @param ruleId string
   * */
  getRuleFromData = (ruleId) => {
    const { data } = this.state;
    const currentRule = data.configRules.filter(
      (item) => item.configRule.id === ruleId
    )[0];
    return { ...currentRule };
  };

  /**
   * @description 编辑规则详情
   * @param rule tableItem
   * */
  HandleViewRule = (rule) => {
    this.setState({
      currentRule: this.getRuleFromData(rule.id),
      title: messages("common.edit"),
      showRuleDetail: true,
    });
  };

  /**
   * @description 保存处理
   *
   * */
  handleSave = () => {
    this.getData();
  };

  /**
   * @description 回退按钮
   * */
  handleBack = () => {
    this.context.router.push(this.state.configurationDetail.url);
  };

  render() {
    const {
      loading,
      data,
      tableData,
      columns,
      showRuleDetail,
      title,
      currentRule,
    } = this.state;
    return (
      <div className="configuration-center-detail">
        {loading ? (
          <Spin />
        ) : (
          <div>
            <Card bordered={false}>
              {/* 规则配置*/}
              <p>
                {data.configItem.itemName}
                {messages("setting.key274" /*规则配置*/)}
                {/*{messages('configuration.detail.ruleConfig')}*/}
              </p>
              {/*说明*/}
              <p>
                {/*{messages('configuration.detail.explain')}*/}
                {messages("setting.key275" /*说明*/)}：
                {data.configItem.description}
              </p>
              {/*默认规则*/}
              <p>
                {/*{messages('configuration.detail.fitRules')}*/}
                {messages("setting.key276" /*当符合规则时则按默认规则执行*/)}：
                {data.configItem.defaultValueDesc}
              </p>
              <p>
                {
                  messages(
                    "setting.key1801"
                  ) /*注：规则的优先级数字可重复，存在优先级数字重复的规则时，排序靠前的规则优先级更高。*/
                }
              </p>
            </Card>
            <div className="table-header">
              <div className="table-header-buttons">
                <Button type="primary" onClick={this.handleAdd}>
                  {/* 新建规则*/} {messages("setting.key277" /*新建规则*/)}
                  {/*{messages('configuration.detail.addRule')}*/}
                </Button>
              </div>
            </div>
            <ResizeTable
              columns={columns}
              style={{ marginBottom: "24px" }}
              dataSource={tableData}
              onRow={(rule) => ({ onClick: () => this.HandleViewRule(rule) })}
              rowKey="id"
              bordered
              pagination={false}
              size="middle"
            />
            <a
              style={{ fontSize: "14px", paddingBottom: "20px" }}
              onClick={this.handleBack}
            >
              <Icon type="rollback" style={{ marginRight: "5px" }} />
              {messages("common.back")}
            </a>
            <SlideFrame
              show={showRuleDetail}
              title={title}
              hasFooter={false}
              hasMask
              params={{
                currentRule,
                configItem: data.configItem,
                configFactors: data.configFactors,
                showRuleDetail,
                handleSave: () => this.handleSave(),
              }}
              content={EditRule}
              onClose={() => {
                this.setState({ showRuleDetail: false });
              }}
              afterClose={() => {
                this.setState({ showRuleDetail: false });
              }}
            />
          </div>
        )}
      </div>
    );
  }
}

ConfigurationDetail.contextTypes = {
  router: React.PropTypes.object,
};

function mapStateToProps(state) {
  return {
    tenantInfo: state.login.tenant,
  };
}

export default connect(mapStateToProps)(ConfigurationDetail);
